package com.yayun.merchant.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

/**
 * 图书封面工具类
 */
public class BookCoverUtils {
    private static final Logger log = LoggerFactory.getLogger(BookCoverUtils.class);
    private static final String DOUBAN_API_URL = "https://api.douban.com/v2/book/isbn/";
    private static final String GOOGLE_BOOKS_API_URL = "https://www.googleapis.com/books/v1/volumes?q=isbn:";
    private static final RestTemplate restTemplate = new RestTemplate();
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 搜索图书封面
     * @param isbn ISBN号
     * @return 封面URL
     */
    public static String searchBookCover(String isbn) {
        if (isbn == null || isbn.trim().isEmpty()) {
            return null;
        }

        // 清理ISBN中的特殊字符
        isbn = isbn.replaceAll("[^0-9X]", "");

        try {
            // 先尝试使用Google Books API
            String googleUrl = GOOGLE_BOOKS_API_URL + isbn;
            String googleResponse = restTemplate.getForObject(googleUrl, String.class);
            JsonNode googleRoot = objectMapper.readTree(googleResponse);
            
            if (googleRoot.has("items") && googleRoot.get("items").size() > 0) {
                JsonNode volumeInfo = googleRoot.get("items").get(0).get("volumeInfo");
                if (volumeInfo.has("imageLinks")) {
                    String thumbnail = volumeInfo.get("imageLinks").get("thumbnail").asText();
                    // 将http链接转换为https
                    return thumbnail.replace("http://", "https://");
                }
            }

            // 如果Google Books API没有结果，尝试豆瓣API
            String doubanUrl = DOUBAN_API_URL + isbn;
            String doubanResponse = restTemplate.getForObject(doubanUrl, String.class);
            JsonNode doubanRoot = objectMapper.readTree(doubanResponse);
            
            if (doubanRoot.has("image")) {
                return doubanRoot.get("image").asText();
            }
        } catch (Exception e) {
            log.error("搜索图书封面失败: " + e.getMessage());
        }

        return null;
    }
} 